//
//  PersonHomeViewController.m
//  B2C
//
//  Created by 李小龙 on 2017/7/27.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "PersonHomeViewController.h"
#import "PersonHomeTableViewCell.h"
#import "EditNameViewController.h"
#import "ASBirthSelectSheet.h"
#import "LXLChangePhoneViewController.h"
#import "EditPassWordViewController.h"
#import "PcaModel.h"

@interface PersonHomeViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) UIImagePickerController *imagePickerController;

@property (nonatomic, strong) NSMutableArray *pcaArray;
@end

@implementation PersonHomeViewController
#pragma mark - get
- (UIImagePickerController *)imagePickerController {
    if (!_imagePickerController) {
        //初始化图片选择器
        _imagePickerController = [[UIImagePickerController alloc]init];
        _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
    }
    return _imagePickerController;
}
- (NSMutableArray *)pcaArray {
    if (!_pcaArray) {
        _pcaArray = [[NSMutableArray alloc] init];
    }
    return _pcaArray;
}
#pragma mark - viewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"个人资料";
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}
#pragma mark - 网络请求
- (void)uploadSex:(NSString *)sex {
    NSString *uploadSex = @"1";
    if ([sex isEqualToString:@"女"]) {
        uploadSex = @"0";
    }
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Save_MSex parameters:@{@"msex":uploadSex} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [UserInfo shareInstance].user.msex = uploadSex;
            PersonHomeTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
            
            [cell.secondContentLabel setText:sex];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
- (void)uploadBirthday:(NSString *)birthday {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Save_Mbirthday parameters:@{@"mbirthday":birthday} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [UserInfo shareInstance].user.mbirthday = birthday;
            PersonHomeTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:1]];
            [cell.secondContentLabel setText:birthday];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
- (void)getPcaData {
    if (self.pcaArray.count > 0) {
        // 直接显示
        [self showPcaPicker];
        return;
    }
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Get_Pca parameters:nil success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [self.pcaArray removeAllObjects];
            NSArray *array = responseObject[@"data"];
            for (NSDictionary *dic in array) {
                PcaModel *model = [PcaModel mj_objectWithKeyValues:dic];
                [self.pcaArray addObject:model];
            }
            // 显示地区选择的picker
            [self showPcaPicker];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
- (void)uploadAid:(NSString *)aid {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Save_Aid parameters:@{@"aid":aid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
//            PersonHomeTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:1]];
            [[UserInfo shareInstance] updateUserInterfaceModel:^(BOOL success) {
                [self.tableView reloadData];
            }];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
- (void)showPcaPicker {
    UIWindow *windowKey = [UIApplication sharedApplication].keyWindow;
    
    ASBirthSelectSheet *datesheet = [[ASBirthSelectSheet alloc] initWithFrame:windowKey.bounds type:sheetTypePca];
    datesheet.pcaArray = self.pcaArray;
    datesheet.GetSelectDate = ^(NSString *dateStr, NSString *addressStr) {
        // 修改地区接口
        NSLog(@"选择的区ID %@",dateStr);
        [self uploadAid:dateStr];
    };
    [windowKey addSubview:datesheet];
    [datesheet showPickerView];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 1;
        case 1:
            return 3;
        case 2:
            return 3;
        case 3:
            return 1;
        default:
            return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PersonHomeTableViewCell *cell = [PersonHomeTableViewCell personHomeCellWithTableView:tableView indexPath:indexPath];
    switch (indexPath.section) {
        case 0:
            [cell.headerImageView sd_setImageWithURL:GetUrl([UserInfo shareInstance].user.mimg) placeholderImage:PlaceholderImageHeader];
            break;
        case 1:
        {
            switch (indexPath.row) {
                case 0:
                {
                    [cell.secondTitleLabel setText:@"昵称"];
                    [cell.secondContentLabel setText:TextIsNotNil([UserInfo shareInstance].user.mnickname)?[UserInfo shareInstance].user.mnickname:@"输入昵称"];
                    break;
                }
                case 1:
                {
                    [cell.secondTitleLabel setText:@"性别"];
                    if (TextIsNotNil([UserInfo shareInstance].user.msex)) {
                        if ([[UserInfo shareInstance].user.msex isEqualToString:@"0"]) {
                            [cell.secondContentLabel setText:@"女"];
                        } else {
                            [cell.secondContentLabel setText:@"男"];
                        }
                    } else {
                        [cell.secondContentLabel setText:@"编辑性别"];
                    }
                    break;
                }
                case 2:
                {
                    [cell.secondTitleLabel setText:@"生日"];
                    [cell.secondContentLabel setText:TextIsNotNil([UserInfo shareInstance].user.mbirthday)?[UserInfo shareInstance].user.mbirthday:@"编辑生日"];
                    break;
                }
                default:
                    break;
            }
            break;
        }
        case 2:
        {
            switch (indexPath.row) {
                case 0:
                {
                    [cell.secondTitleLabel setText:@"手机号"];
                    [cell.secondContentLabel setText:TextIsNotNil([UserInfo shareInstance].user.mtel)?[UserInfo shareInstance].user.mtel:@"输入手机号"];
                    break;
                }
                case 1:
                {
                    [cell.secondTitleLabel setText:@"地区"];
                    NSString *address = [NSString stringWithFormat:@"%@%@%@",[UserInfo shareInstance].user.pname,[UserInfo shareInstance].user.cname,[UserInfo shareInstance].user.aname];
                    [cell.secondContentLabel setText:TextIsNotNil(address)?address:@"选择地区"];
                    break;
                }
                case 2:
                {
                    [cell.secondTitleLabel setText:@"真实姓名"];
                    [cell.secondContentLabel setText:TextIsNotNil([UserInfo shareInstance].user.mname)?[UserInfo shareInstance].user.mname:@"输入姓名"];
                    break;
                }
                default:
                    break;
            }
            break;
        }
        case 3:
        {
            switch (indexPath.row) {
                case 0:
                {
                    [cell.secondTitleLabel setText:@"修改密码"];
                    [cell.secondContentLabel setText:@""];
                    break;
                }
                    
                default:
                    break;
            }
            break;
        }
        default:
            break;
    }
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
            return 80;
        case 1: case 2: case 3:
            return 44;
        default:
            return 0;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.width, 5)];
    [view setBackgroundColor:[UIColor clearColor]];
    return view;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    dispatch_async(dispatch_get_main_queue(), ^{
        __weak typeof(self) weakSelf = self;
        switch (indexPath.section) {
            case 0:
            {
                [self showAlertWithTitleArray:@[@"拍照",@"相册",@"取消"] title:nil message:nil alertStyle:UIAlertControllerStyleActionSheet];
                self.alertBlock = ^(NSString *actionTitle) {
                    if ([actionTitle isEqualToString:@"拍照"]) {
                        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                            [MBProgressHUD myShowHUDAddedTo:weakSelf.view labelText:@"不支持摄像头,请查看摄像权限！" animated:YES];
                            return;
                        }
                        
                        weakSelf.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                        [weakSelf presentViewController:weakSelf.imagePickerController animated:YES completion:^{
                            //
                        }];
                    }
                    if ([actionTitle isEqualToString:@"相册"]) {
                        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                            [MBProgressHUD myShowHUDAddedTo:weakSelf.view labelText:@"图片库不可用,请查看隐私权限！" animated:YES];
                            return;
                        }
                        weakSelf.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                        [weakSelf presentViewController:weakSelf.imagePickerController animated:YES completion:^{
                            
                        }];
                    }
                    
                };
            } break;
            case 1:
            {
                switch (indexPath.row) {
                    case 0:
                    {
                        EditNameViewController *editVC = [[EditNameViewController alloc] init];
                        editVC.type = EditTypeNickName;
                        [self.navigationController pushViewController:editVC animated:YES];
                        
                        break;
                    }
                    case 1:
                    {
                        [self showAlertWithTitleArray:@[@"男",@"女",@"取消"] title:nil message:nil alertStyle:UIAlertControllerStyleActionSheet];
                        self.alertBlock = ^(NSString *actionTitle) {
                            if ([actionTitle isEqualToString:@"男"] || [actionTitle isEqualToString:@"女"]) {
                                // 修改性别的接口
                                [weakSelf uploadSex:actionTitle];
                            }
                        };
                        break;
                    }
                    case 2:
                    {
                        UIWindow *windowKey = [UIApplication sharedApplication].keyWindow;
                        
                        ASBirthSelectSheet *datesheet = [[ASBirthSelectSheet alloc] initWithFrame:windowKey.bounds type:sheetTypeDate];
                        datesheet.selectDate = [DateSomeThing getDateStr:[NSDate date] dateFormat:@"yyyy-MM-dd"];
                        datesheet.GetSelectDate = ^(NSString *dateStr, NSString *addressStr) {
                            // 修改生日接口
                            [weakSelf uploadBirthday:dateStr];
                        };
                        [windowKey addSubview:datesheet];
                        [datesheet showPickerView];
                        break;
                    }
                    default:
                        break;
                }
            } break;
            case 2:
            {
                switch (indexPath.row) {
                    case 0:
                    {
                        LXLChangePhoneViewController *changePhoneVC = [[LXLChangePhoneViewController alloc] init];
                        [self.navigationController pushViewController:changePhoneVC animated:YES];
                        break;
                    }
                    case 1:
                    {
                        [self getPcaData];
                        break;
                    }
                    case 2:
                    {
                        EditNameViewController *editVC = [[EditNameViewController alloc] init];
                        editVC.type = EditTypeName;
                        [self.navigationController pushViewController:editVC animated:YES];
                        break;
                    }
                    default:
                        break;
                }
            } break;
            case 3:
            {
                switch (indexPath.row) {
                    case 0:
                    {
                        EditPassWordViewController *passwordVC = [[EditPassWordViewController alloc] init];
                        [self.navigationController pushViewController:passwordVC animated:YES];
                        break;
                    }
                        
                    default:
                        break;
                }
            } break;
            default:
                break;
        }
    });
}
#pragma mark - 系统相册和相机
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary*)info{
    
    
    UIImage *image = (UIImage *)[info objectForKey:@"UIImagePickerControllerEditedImage"];
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);//把图片存到图片库
    }
    
    //关闭图片选择器
    [self dismissViewControllerAnimated:YES completion:nil];
    
    //上传头像接口 修改本地数据源
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking UPLoad:URL_Upload_Mimg images:image progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dics = responseObject;
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([[dics objectForKey:@"code"] isEqualToString:@"200"]) {
            [UserInfo shareInstance].user.mimg = dics[@"data"][@"url"];
            [[UserInfo shareInstance] updateUserModel];
            
            PersonHomeTableViewCell *cell = [weakSelf.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            [cell.headerImageView setImage:image];
        } else {
            [MBProgressHUD showError:weakSelf.view title:dics[@"message"] code:[dics objectForKey:@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
